package com.javid.study.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class MyWebsocket {

    /**
     * 存放每个客户端对应的Session对象。
     */
    private static Map<String, Session> socketMap = new ConcurrentHashMap<>();


    public MyWebsocket() {
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        try {
            String key = getKey(session);
            if (key != null) {
                // 存放 session
                socketMap.put(key, session);
                log.info("key:" + key);
                log.info("session:" + session);
                sendMessageToUser("连接成功", key);
                log.info("连接成功");
            } else {
                log.info("socket链接session保存失败！当前key为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据session获取key,自定义，用于标示每个session
     *
     * @param session
     * @return
     */
    public String getKey(Session session) {
        String key = null;
        try {
            String identity = String.valueOf(session.getRequestParameterMap().get("identity").get(0));
            key = identity;
        } catch (Exception e) {
            log.info("根据session获取key失败：{}", e.getMessage());
            e.printStackTrace();
        }
        return key;
    }

    /**
     * 根据identity获取key
     *
     * @return
     */
    public String getKey(String identity) {
        return identity;
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        try {
            String key = getKey(session);
            if (key != null) {
                socketMap.remove(key);
            }
            log.info("有一连接关闭 ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        String key = getKey(session);
        if (!socketMap.containsKey(key)){
            socketMap.put(key, session);
        }
        log.info("收到客户端：" + key + "的消息：" + message + " ,当前socket数量：" + socketMap.size());
        sendMessageToUser("保持连接", key);
    }


    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        onClose(session);
        log.info("websocket连接发生错误{}", error.getMessage());
    }

    /**
     * 发送信息给指定用户
     *
     * @param message
     * @param key
     * @return
     */
    public boolean sendMessageToUser(String message, String key) {
        if (key == null) {
            return false;
        }
        Session session = socketMap.get(key);
        if (session == null) {
            return false;
        }
        if (!session.isOpen()) {
            return false;
        }
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.info("发送消息失败----->{{}}", e.getMessage());
        }
        return true;
    }

    /**
     * 发送信息给所有用户
     *
     * @return
     */
    public boolean sendMessageToAllUser() {
        if (socketMap.size() == 0) {
            return false;
        }
        for (String key:socketMap.keySet()){
            Session session = socketMap.get(key);
            if (session == null) {
                return false;
            }
            if (!session.isOpen()) {
                return false;
            }
            try {
                session.getBasicRemote().sendText("modify");
            } catch (IOException e) {
                log.info("发送消息失败----->{{}}", e.getMessage());
            }
        }
        return true;
    }

}

